<template>
  <el-dialog title="新增员工" :visible="showDialog" width="40%" @close="close">
    <el-form
      ref="addEmployeeForm"
      :model="addEmployeeForm"
      label-width="80px"
      :rules="rules"
      @click.native="showTree = false"
    >
      <el-form-item label="姓名" prop="username">
        <el-input
          v-model="addEmployeeForm.username"
          size="small"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="addEmployeeForm.mobile"
          size="small"
          placeholder="请输入手机号"
        />
      </el-form-item>
      <el-form-item label="入职时间" prop="timeOfEntry">
        <el-date-picker
          v-model="addEmployeeForm.timeOfEntry"
          type="date"
          placeholder="请选择入职时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select v-model="addEmployeeForm.formOfEmployment" placeholder="请选择">
          <el-option label="正式" :value="1"></el-option>
          <el-option label="非正式" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input
          v-model="addEmployeeForm.workNumber"
          size="small"
          placeholder="请输入工号"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <!-- @click.native 监听组件根元素的原生事件 -->
        <el-input
          v-model="addEmployeeForm.departmentName"
          placeholder="请选择部门"
          @click.native.stop="showTree = true"
        />
        <div v-show="showTree" class="tree-box">
          <el-tree
            :data="departs"
            :props="defaultProps"
            :default-expand-all="true"
            :expand-on-click-node="false"
            @node-click="getNodes"
          ></el-tree>
        </div>
      </el-form-item>
      <el-form-item label="转正时间" prop="correctionTime">
        <el-date-picker
          v-model="addEmployeeForm.correctionTime"
          type="date"
          placeholder="请选择转正时间"
        ></el-date-picker>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="addConfirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { validMobile } from '@/utils/validate'
import { reqGetDepartments } from '@/api/departments'
import { reqAddEmployee } from '@/api/employees'
import { tranListToTreeData } from '@/utils'

export default {
  name: 'AddEmployee',
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    const checkMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        return callback(new Error('手机格式错误'))
      } else {
        callback()
      }
    }
    return {
      // 新增员工的表单数据
      addEmployeeForm: {
        username: '',
        mobile: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        correctionTime: '',
      },
      // 树形结构展示数据
      departs: [
        {
          label: '一级 1',
          children: [
            {
              label: '二级 1-1',
              children: [],
            },
          ],
        },
        {
          label: '一级 2',
          children: [
            {
              label: '二级 2-1',
              children: [],
            },
            {
              label: '二级 2-2',
              children: [],
            },
          ],
        },
        {
          label: '一级 3',
          children: [
            {
              label: '二级 3-1',
              children: [],
            },
            {
              label: '二级 3-2',
              children: [],
            },
          ],
        },
      ],
      // 树形结构配置项
      defaultProps: {
        label: 'name',
        children: 'children',
      },
      // 表单校验规则
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
        timeOfEntry: [{ required: true, message: '请选择入职时间', trigger: 'blur' }],
        formOfEmployment: [
          { required: true, message: '请选择聘用形式', trigger: 'blur' },
        ],
        workNumber: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        departmentName: [{ required: true, message: '请选择部门', trigger: 'change' }],
        correctionTime: [{ required: true, message: '请选择转正时间', trigger: 'blur' }],
      },
      showTree: false, // 控制部门树形结构的显示
    }
  },
  created() {
    // 调用获取部门的方法
    this.loadDeparts()
  },

  methods: {
    // 一、关闭对话框触发的方法
    close() {
      this.$emit('closeDialog', false)
      this.$refs['addEmployeeForm'].resetFields()
      this.addEmployeeForm = {}
    },

    // 二、点击部门树形结构,获取相应的部门
    getNodes(nodeData) {
      // console.log(nodeData)
      this.addEmployeeForm.departmentName = nodeData.name
      this.showTree = false
    },

    // 三、获取部门信息的方法
    async loadDeparts() {
      const data = await reqGetDepartments()
      // console.log(data)
      this.departs = tranListToTreeData(data.depts, '')
      // console.log(this.departs)
      // console.log(formatDateString(this.timeOfEntry))
    },

    // 四、点击确认按钮后触发的方法
    addConfirm() {
      // 1.校验表单
      this.$refs['addEmployeeForm'].validate(async valid => {
        if (valid) {
          // 1.1 校验通过,发送添加请求,提示成功信息,让父组件关闭对话框并刷新页面
          await reqAddEmployee(this.addEmployeeForm)
          this.$message.success('添加成功')
          this.$emit('closeDialog', false)
          this.$emit('addEmployee')
        } else {
          // 1.2 校验失败
          this.$message.error('请填写必须项')
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.el-input {
  width: 70%;
}
.tree-box {
  position: absolute;
  width: 70%;
  min-height: 50px;
  max-height: 200px;
  left: 0;
  top: 45px;
  z-index: 100;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 0 5px;
  overflow: auto;
  background-color: #fff;
  .el-tree {
    color: #666;
  }
}
::v-deep {
  .el-tree-node__expand-icon.expanded,
  .el-tree-node__expand-icon.is-leaf {
    display: none;
  }
}
</style>
